﻿using System;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using ESRI.ArcGIS.Client;
using ESRI.ArcGIS.Client.Local;
using DGIS.Map.Templetes;
using DGIS.Map.UserControls;
using DGIS.Model;
using System.Collections.Generic;
using System.Timers;
using DGIS.Map.Layers;
using System.Text;
using System.Windows.Media.Imaging;
using System.Windows.Controls;
using System.Linq;

namespace DGIS.Map
{
    /// <summary>
    /// 地图视图显示查询结果委托
    /// </summary>
    /// <param name="items"></param>
    public delegate void ShowGSCloudExtent(List<GSCloud> items);

    /// <summary>
    /// 地图绘制图形委托
    /// </summary>
    /// <param name="type">绘制类型</param>
    public delegate void DrawGeometry(int type);

    /// <summary>
    /// 地图已知坐标绘制面
    /// </summary>
    /// <param name="points"></param>
    public delegate void DrawPolygon(List<double[]> points);

    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        #region 局部变量

        private Storyboard _closeStoryboard;//窗体关闭动画
        private bool _isClosed;//窗体是否关闭
        private System.Windows.Forms.NotifyIcon _notifyIcon;//右下角图标
        private DateTime _sysDateTime;//系统时间

        //影像标记图层
        private GraphicsLayer _gsImgGraphicsLayer;

        //临时绘制图层
        private GraphicsLayer _graphicsLayer;

        //地图绘制
        private Draw _mapDraw;

        //地图全图范围
        private ESRI.ArcGIS.Client.Geometry.Envelope _mapExtent;

        //地图视图数据集合
        List<GSCloud> _mapItems;

        #endregion

        public MainWindow(GSUser user)
        {
            InitializeComponent();

            try
            {
                Init();
                this.UserName.Text = user.Name;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        public MainWindow()
        {
            InitializeComponent();

            try
            {
                Init();
                this.UserName.Text = "未登录";
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        #region 事件

        #region 系统事件

        //标题拖拽事件
        private void GridDrag_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            this.DragMove();
        }

        //设置事件
        private void Setting_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            DGIS.Control.GsCloudControl gsCloudControl = new Control.GsCloudControl();
            gsCloudControl.UpdateGSDataSets();
        }

        //窗体尺寸改变事件
        private void Window_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            if (this.ActualHeight > SystemParameters.WorkArea.Height || this.ActualWidth > SystemParameters.WorkArea.Width)
            {
                this.WindowState = System.Windows.WindowState.Normal;
                Max_MouseLeftButtonDown(null, null);
            }
        }

        //退出
        private void Window_Closed(object sender, EventArgs e)
        {
            _notifyIcon.Visible = false;
            Environment.Exit(0);
        }

        //显示主窗体
        private void Show(object sender, EventArgs e)
        {
            this.Visibility = System.Windows.Visibility.Visible;
            this.ShowInTaskbar = true;
            this.Activate();
        }

        //缩小到托盘
        private void Hide(object sender, EventArgs e)
        {
            this.ShowInTaskbar = false;
            this.Visibility = System.Windows.Visibility.Hidden;
        }

        //退出系统
        private void Close(object sender, EventArgs e)
        {
            if (!_isClosed)
            {
                //关闭窗体动画实现
                _closeStoryboard.Completed += delegate
                {
                    _notifyIcon.Visible = false;

                    _isClosed = true;
                    Environment.Exit(0);
                };
                _closeStoryboard.Begin();
            }
        }

        //tab选项卡切换事件
        private void MainTabControl_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            this.InfoGrid.Visibility = Visibility.Hidden;
            foreach (TabItem tab in this.MainTabControl.Items)
            {
                tab.Width = (tab.Visibility == Visibility.Hidden) ? 0 : 70;
            }
        }

        #endregion

        #region 动画效果事件

        private void Close_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (System.Windows.MessageBox.Show("是否确认退出？", "", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
            {
                if (!_isClosed)
                {
                    //关闭窗体动画实现
                    _closeStoryboard.Completed += delegate
                    {
                        _isClosed = true;
                        Environment.Exit(0);
                    };
                    _closeStoryboard.Begin();
                }
            }
        }

        private void Close_MouseEnter(object sender, System.Windows.Input.MouseEventArgs e)
        {
            this.CloseRectangle.Fill = new SolidColorBrush(Color.FromArgb(255, 131, 1, 17));
        }

        private void Close_MouseLeave(object sender, System.Windows.Input.MouseEventArgs e)
        {
            this.CloseRectangle.Fill = new SolidColorBrush(Color.FromArgb(0, 131, 1, 17));
        }

        private void Max_MouseEnter(object sender, System.Windows.Input.MouseEventArgs e)
        {
            this.MaxRectangle.Fill = new SolidColorBrush(Color.FromArgb(255, 131, 1, 17));
        }

        private void Max_MouseLeave(object sender, System.Windows.Input.MouseEventArgs e)
        {
            this.MaxRectangle.Fill = new SolidColorBrush(Color.FromArgb(0, 131, 1, 17));
        }

        Rect rcnormal;//定义一个全局rect记录还原状态下窗口的位置和大小。
        private void Max_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            _notifyIcon.Visible = false;
            //this.WindowState = (this.WindowState == WindowState.Maximized) ? WindowState.Normal : WindowState.Maximized;

            if (this.ActualHeight < SystemParameters.WorkArea.Height || this.ActualWidth < SystemParameters.WorkArea.Width)
            {
                rcnormal = new Rect(this.Left, this.Top, this.Width, this.Height);//保存下当前位置与大小
                this.Left = 0;//设置位置
                this.Top = 0;
                Rect rc = SystemParameters.WorkArea;//获取工作区大小
                this.Width = rc.Width;
                this.Height = rc.Height;
            }
            else
            {
                this.Left = rcnormal.Left;
                this.Top = rcnormal.Top;
                this.Width = rcnormal.Width;
                this.Height = rcnormal.Height;
            }
        }

        private void Min_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            //this.WindowState = WindowState.Minimized;
            this.ShowInTaskbar = false;
            _notifyIcon.Visible = true;
            this.Visibility = System.Windows.Visibility.Hidden;
        }

        private void Min_MouseEnter(object sender, System.Windows.Input.MouseEventArgs e)
        {
            this.MinRectangle.Fill = new SolidColorBrush(Color.FromArgb(255, 131, 1, 17));
        }

        private void Min_MouseLeave(object sender, System.Windows.Input.MouseEventArgs e)
        {
            this.MinRectangle.Fill = new SolidColorBrush(Color.FromArgb(0, 255, 0, 17));
        }

        #endregion

        #region　菜单按钮事件

        private void MapMenuItem_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            DisSelectMenuItems(sender as Templetes.MenuItem);
            this.MainTabControl.SelectedIndex = 0;
        }

        private void SearchMenuItem_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            DisSelectMenuItems(sender as Templetes.MenuItem);
            this.SearchTabItem.Visibility = Visibility.Visible;
            this.MainTabControl.SelectedIndex = 1;

            if (this.SearchGrid.Children.Count == 0)
            {
                SearchControl control = new SearchControl();
                control.showGSCloudExtent += ShowGSCloudExtent;
                control.drawGeomety += DrawGeomety;
                control.drawPolygon += DrawPolygonByPoints;

                this.SearchGrid.Children.Add(control);
            }
        }

        private void DownloadMenuItem_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            DisSelectMenuItems(sender as Templetes.MenuItem);

            this.DownloadTabItem.Visibility = Visibility.Visible;
            this.MainTabControl.SelectedIndex = 2;

            if (this.DownloadGrid.Children.Count == 0)
            {
                DownloadControl control = new DownloadControl();
                this.DownloadGrid.Children.Add(control);
            }
        }

        private void MsgMenuItem_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            DisSelectMenuItems(sender as Templetes.MenuItem);

            this.AboutTabItem.Visibility = Visibility.Visible;
            this.MainTabControl.SelectedIndex = 3;

            if (this.AboutGrid.Children.Count == 0)
            {
                AboutControl control = new AboutControl();
                this.AboutGrid.Children.Add(control);
            }
        }

        /// <summary>
        /// 变化按钮选中状态
        /// </summary>
        /// <param name="item"></param>
        private void DisSelectMenuItems(Templetes.MenuItem item)
        {
            foreach (Templetes.MenuItem control in this.MenuWrapPanel.Children)
            {
                control.Selected = (control == item);
            }
        }

        #endregion        

        #region 地图事件

        //地图鼠标经过事件
        private void Map_MouseMove(object sender, MouseEventArgs e)
        {
            var point = this.Map.ScreenToMap(e.GetPosition(this.Map));
            var pt = XYToLonLat(point.X, point.Y);

            this.LonText.Text = Math.Round(pt[0], 2).ToString();
            this.LatText.Text = Math.Round(pt[1], 2).ToString();
        }

        //地图鼠标进入事件
        private void Map_MouseEnter(object sender, MouseEventArgs e)
        {
            if (_mapDraw != null)
                this.Cursor = _mapDraw.IsEnabled ? Cursors.Cross : Cursors.Arrow;
        }

        //地图鼠标离开事件
        private void Map_MouseLeave(object sender, MouseEventArgs e)
        {
            this.Cursor = Cursors.Arrow;
        }

        //标记图层移动事件
        private void graphicsLayer_MouseMove(object sender, GraphicMouseEventArgs e)
        {

        }

        //标记图层选中点击事件
        private void graphicsLayer_MouseLeftButtonDown(object sender, GraphicMouseButtonEventArgs e)
        {
            Graphic graphic = e.Graphic;
            graphic.Selected = !graphic.Selected;

            graphic.Symbol = new ESRI.ArcGIS.Client.Symbols.SimpleFillSymbol()
            {
                BorderBrush = graphic.Selected ? Brushes.Red : Brushes.Blue,
                Fill = new SolidColorBrush(graphic.Selected ? Color.FromArgb(100, 252, 96, 96) : Color.FromArgb(100, 0, 174, 239))
            };

            if (graphic.Selected)
            {
                this.DataidText.Text = graphic.Attributes["dataid"].ToString();
                this.PathText.Text = graphic.Attributes["path"]!=null? graphic.Attributes["path"].ToString():"";
                this.RowText.Text = graphic.Attributes["row"]!=null?graphic.Attributes["row"].ToString():"";
                this.DatadateText.Text = graphic.Attributes["datadate"] != null ? graphic.Attributes["datadate"].ToString() : "未知";
                this.CloudcoverText.Text = graphic.Attributes["cloudcover"] != null ? graphic.Attributes["cloudcover"].ToString() : "未知";
                this.DownloadBtn.Tag = graphic.Attributes["dataid"].ToString();
            }

            this.InfoGrid.Visibility = graphic.Selected ? Visibility.Visible : Visibility.Hidden;

            DoubleAnimation dbAnimation = new DoubleAnimation();
            dbAnimation.From = graphic.Selected ? 0 : 1;
            dbAnimation.To = graphic.Selected ? 1 : 0;
            dbAnimation.Duration = new Duration(TimeSpan.FromMilliseconds(500));
            dbAnimation.FillBehavior = FillBehavior.Stop;
            this.InfoGrid.BeginAnimation(OpacityProperty, dbAnimation);

            this.InfoGrid.Opacity = graphic.Selected ? 1 : 0;
        }

        //放大
        private void ZoomIn_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            this.Map.Zoom(2);
        }

        //缩小
        private void ZoomOut_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            this.Map.Zoom(0.5);
        }

        //全图
        private void FullMapButton_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            this.Map.Extent = _mapExtent;
        }

        //清除
        private void ClearButton_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            _graphicsLayer.Graphics.Clear();
        }

        //绘制完成事件
        private void Draw_DrawComplete(object sender, DrawEventArgs e)
        {
            //获取绘制图形坐标
            List<ESRI.ArcGIS.Client.Geometry.MapPoint> points = GetGeometryPoints(e.Geometry);
            List<double[]> pts = new List<double[]>();

            for (int i = 0; i < points.Count; i++)
            {
                var point = points[i];

                double[] pt = XYToLonLat(point.X, point.Y);
                pts.Add(pt);
            }

            DrawPolygonByPoints(pts);
        }
        
        //下载按钮
        private void DownloadBtn_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            Image image = sender as Image;
            string dataid = image.Tag.ToString();

            GSCloud item = _mapItems.FirstOrDefault(x => x.dataid == dataid);

            if (AppConstant.DownloadProgressList.Any(x => x.Url == item.url))
            {
                MessageBox.Show("该任务已经存在");
            }
            else if (!string.IsNullOrEmpty(item.url))
            {
                DGIS.Control.DownloadControl downloadControl = new DGIS.Control.DownloadControl();
                List<DownloadFile> completeTasks = downloadControl.GetCompleteTasks();
                if (completeTasks.Any(x => x.Url == item.url))
                {
                    MessageBox.Show("已下载过该数据");
                }
                else
                {
                    this.Dispatcher.Invoke(new Action(() =>
                    {
                        string extension;
                        BitmapImage ico;
                        GetDownloadFileTypeAndIco(out extension, out ico, null);

                        if (item.filesize == null)
                            item.filesize = 0;

                        DownloadFile downloadItem = new DownloadFile()
                        {
                            FileName = item.dataid + extension,
                            FileSize = item.filesize.Value,
                            ProgressValue = -1,
                            Speed = 0,
                            IconSource = ico,
                            Url = item.url,
                            DataId = item.dataid
                        };

                        if (downloadControl.Download(downloadItem, false, true, ((id, status) =>
                        {
                            if (status == 3)
                            {
                                var fileTask = AppConstant.DownloadProgressList.FirstOrDefault(x => x.DataId == id);

                                System.Windows.Application.Current.Dispatcher.Invoke((Action)(() => {
                                    AppConstant.DownloadProgressList.Remove(fileTask);
                                }));
                            }

                            return 0;
                        })))
                        {
                            AppConstant.DownloadProgressList.Add(downloadItem);
                        }
                        else
                        {
                            MessageBox.Show("下载失败");
                        }
                    }));
                }
            }
            else
            {
                MessageBox.Show("获取下载地址失败");
            }
        }

        #endregion

        #endregion

        #region 方法

        /// <summary>
        /// 初始化
        /// </summary>
        private void Init()
        {
            //找到资源定义的故事板
            _closeStoryboard = this.Resources["WindowClose"] as Storyboard;

            //托盘图标
            _notifyIcon = new System.Windows.Forms.NotifyIcon();
            _notifyIcon.Text = this.Title;
            _notifyIcon.Icon = System.Drawing.Icon.ExtractAssociatedIcon(System.Windows.Forms.Application.ExecutablePath);
            _notifyIcon.Visible = false;
            //打开菜单项
            System.Windows.Forms.MenuItem open = new System.Windows.Forms.MenuItem("打开");
            open.Click += new EventHandler(Show);
            //退出菜单项
            System.Windows.Forms.MenuItem exit = new System.Windows.Forms.MenuItem("退出");
            exit.Click += new EventHandler(Close);
            //关联托盘控件
            System.Windows.Forms.MenuItem[] childen = new System.Windows.Forms.MenuItem[] { open, exit };
            _notifyIcon.ContextMenu = new System.Windows.Forms.ContextMenu(childen);

            _notifyIcon.MouseDoubleClick += new System.Windows.Forms.MouseEventHandler((o, e) =>
            {
                if (e.Button == System.Windows.Forms.MouseButtons.Left) this.Show(o, e);
            });

            //实例化下载文件集合
            AppConstant.DownloadProgressList = new System.Collections.ObjectModel.ObservableCollection<DownloadFile>();

            //初始化地图
            InitMap();

            //获取未完成下载任务
            InitDownloadTasks();

            //初始化时间            
            Timer timer = new Timer(1000);
            timer.Elapsed += Timer_Elapsed;
            timer.Start();

            //填充tab
            SearchControl control = new SearchControl();
            control.showGSCloudExtent += ShowGSCloudExtent;
            control.drawGeomety += DrawGeomety;
            control.drawPolygon += DrawPolygonByPoints;
            this.SearchGrid.Children.Add(control);

            DownloadControl control1 = new DownloadControl();
            this.DownloadGrid.Children.Add(control1);

            AboutControl control2 = new AboutControl();
            this.AboutGrid.Children.Add(control2);

        }

        /// <summary>
        /// 初始化地图
        /// </summary>
        private void InitMap()
        {
            

            this.Map.IsLogoVisible = false;

            //加载底图
            BingImgLayer bingImgLayer = new BingImgLayer();
            this.Map.Layers.Add(bingImgLayer);

            

            //加载标记图层
            _graphicsLayer = new GraphicsLayer();
            this.Map.Layers.Add(_graphicsLayer);

            //加载影像标记图层
            _gsImgGraphicsLayer = new GraphicsLayer();
            _gsImgGraphicsLayer.MouseLeftButtonDown += graphicsLayer_MouseLeftButtonDown;
            _gsImgGraphicsLayer.MouseMove += graphicsLayer_MouseMove;
            this.Map.Layers.Add(_gsImgGraphicsLayer);

            //设置地图范围            
            _mapExtent = new ESRI.ArcGIS.Client.Geometry.Envelope(7556383.44002147, 2238920.68181928, 16183667.2293366, 6433224.68181931);
            this.Map.Extent = _mapExtent;

            //初始化地图绘制插件
            _mapDraw = new Draw(this.Map)
            {
                LineSymbol = new ESRI.ArcGIS.Client.Symbols.LineSymbol()
                {
                    Color = Brushes.Red,
                    Width = 2
                },
                FillSymbol = new ESRI.ArcGIS.Client.Symbols.FillSymbol()
                {
                    Fill = new SolidColorBrush(Color.FromArgb(100, 255, 0, 0))
                }
            };
            _mapDraw.DrawComplete += Draw_DrawComplete;
        }

        /// <summary>
        /// 初始化未完成下载任务
        /// </summary>
        private void InitDownloadTasks()
        {
            DGIS.Control.DownloadControl downloadControl = new Control.DownloadControl();
            List<DownloadFile> items = downloadControl.GetResumeTasks();

            foreach (var item in items)
            {
                item.IconSource = GetFileIcon(System.IO.Path.GetExtension(item.FileName));
                item.Status = (int)DownloadFile.DownloadStatus.Stop;

                AppConstant.DownloadProgressList.Add(item);

                DGIS.Control.DownloadControl control = new Control.DownloadControl();
                control.Download(item, true, false, ((id, status) =>
                {
                    if (status == 3)
                    {
                        var fileTask = AppConstant.DownloadProgressList.FirstOrDefault(x => x.DataId == id);
                        System.Windows.Application.Current.Dispatcher.Invoke((Action)(() => {
                            AppConstant.DownloadProgressList.Remove(fileTask);
                        }));
                    }

                    return 0;
                }));
            }
        }

        /// <summary>
        /// 获取文件图标
        /// </summary>
        /// <param name="extension"></param>
        /// <returns></returns>
        private BitmapImage GetFileIcon(string extension)
        {
            string icoPath = "";
            switch (extension.ToLower())
            {
                case ".zip":
                    icoPath = string.Format("{0}Images\\FileIcon\\zip.png", AppDomain.CurrentDomain.BaseDirectory);
                    break;
                case ".hdf":
                    icoPath = string.Format("{0}Images\\FileIcon\\hdf.png", AppDomain.CurrentDomain.BaseDirectory);
                    break;
                case ".tgz":
                    icoPath = string.Format("{0}Images\\FileIcon\\tgz.png", AppDomain.CurrentDomain.BaseDirectory);
                    break;
                case ".tif":
                    icoPath = string.Format("{0}Images\\FileIcon\\bmp.png", AppDomain.CurrentDomain.BaseDirectory);
                    break;
                case ".gz":
                    icoPath = string.Format("{0}Images\\FileIcon\\zip.png", AppDomain.CurrentDomain.BaseDirectory);
                    break;
                default:
                    break;
            }

            BitmapImage bitmapImage = new BitmapImage(new Uri(icoPath));
            return bitmapImage;
        }

        /// <summary>
        /// 时间变化
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            this.DateText.Dispatcher.Invoke(new Action(() =>
            {
                if (_sysDateTime.Year == 1)
                {
                    _sysDateTime = DateTime.Now;
                }
                else
                {
                    _sysDateTime = _sysDateTime.AddSeconds(1);
                }
                this.DateText.Text = _sysDateTime.ToLongTimeString();
            }));
        }

        private void LocalMapService_StartCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            LocalMapService localMapService = sender as LocalMapService;

            ArcGISLocalDynamicMapServiceLayer layer = new ArcGISLocalDynamicMapServiceLayer(localMapService);
            this.Map.Layers.Add(layer);
        }

        /// <summary>
        /// 地图显示查询结果范围
        /// </summary>
        /// <param name="items"></param>
        private void ShowGSCloudExtent(List<GSCloud> items)
        {
            _mapItems = items;
            _gsImgGraphicsLayer.Graphics.Clear();

            foreach (GSCloud item in items)
            {
                List<double[]> pts = item.coordinates;

                ESRI.ArcGIS.Client.Geometry.Polygon polygon = CreatePolygon(pts);
                Graphic graphic = new Graphic()
                {
                    Geometry = polygon,
                    Symbol = new ESRI.ArcGIS.Client.Symbols.SimpleFillSymbol()
                    {
                        BorderBrush = Brushes.Blue,
                        Fill = new SolidColorBrush(Color.FromArgb(100, 0, 174, 239))
                    }
                };
                graphic.Attributes.Add("id", item.id);
                graphic.Attributes.Add("dataid", item.dataid);
                graphic.Attributes.Add("filesize", item.filesize);
                graphic.Attributes.Add("datadate", item.datadate);
                graphic.Attributes.Add("cloudcover", item.cloudcover);
                graphic.Attributes.Add("ct_lat", item.ct_lat);
                graphic.Attributes.Add("ct_long", item.ct_long);
                graphic.Attributes.Add("path", item.path);
                graphic.Attributes.Add("row", item.row);
                graphic.Attributes.Add("url", item.url);

                _gsImgGraphicsLayer.Graphics.Add(graphic);
            }
        }

        /// <summary>
        /// 绘制图形
        /// </summary>
        /// <param name="type"></param>
        private void DrawGeomety(int type)
        {
            switch (type)
            {
                case 0:
                    break;
                case 1:
                    break;
                case 2:
                    DrawRectangle();
                    break;
                case 3:
                    DrawPolygon();
                    break;
                default:
                    break;
            }
            this.MainTabControl.SelectedIndex = 0;
        }

        /// <summary>
        /// 绘制矩形
        /// </summary>
        private void DrawRectangle()
        {
            _mapDraw.DrawMode = DrawMode.Rectangle;
            _mapDraw.IsEnabled = true;
        }

        /// <summary>
        /// 绘制多边形
        /// </summary>
        private void DrawPolygon()
        {
            _mapDraw.DrawMode = DrawMode.Polygon;
            _mapDraw.IsEnabled = true;
        }

        /// <summary>
        /// 根据已知点绘制面
        /// </summary>
        /// <param name="pts"></param>
        private void DrawPolygonByPoints(List<double[]> pts)
        {
            //获取绘制图形坐标
            StringBuilder sb = new StringBuilder();

            for (int i = 0; i < pts.Count; i++)
            {
                var point = pts[i];
                if ((point[0] > 180 || point[0] < -180))
                {
                    point = XYToLonLat(point[0], point[1]);
                    pts[i] = point;
                }

                sb.Append("[");
                sb.Append(point[0]);
                sb.Append(",");
                sb.Append(point[1]);
                sb.Append("]");

                if (i < pts.Count - 1)
                    sb.Append(",");
            }

            AppConstant.SearchPolygonStr = sb.ToString();

            //地图渲染
            Graphic graphic = new Graphic()
            {
                Geometry = CreatePolygon(pts),
                Symbol = new ESRI.ArcGIS.Client.Symbols.SimpleFillSymbol()
                {
                    BorderBrush = Brushes.Red,
                    Fill = new SolidColorBrush(Color.FromArgb(50, 255, 0, 0))
                }
            };
            _graphicsLayer.Graphics.Clear();
            _graphicsLayer.Graphics.Add(graphic);
            _mapDraw.IsEnabled = false;
            this.Cursor = Cursors.Arrow;
            this.MainTabControl.SelectedIndex = 1;
        }

        /// <summary>
        /// 根据点创建面
        /// </summary>
        /// <param name="pts"></param>
        /// <returns></returns>
        private ESRI.ArcGIS.Client.Geometry.Polygon CreatePolygon(List<double[]> pts)
        {
            ESRI.ArcGIS.Client.Geometry.PointCollection points = new ESRI.ArcGIS.Client.Geometry.PointCollection();
            int wkid = (pts[0][0] > 180 || pts[0][0] < -180) ? 4326 : 3857;

            for (int i = 0; i < pts.Count; i++)
            {
                double[] point = pts[i];
                points.Add(new ESRI.ArcGIS.Client.Geometry.MapPoint()
                {
                    X = point[0],
                    Y = point[1],
                    SpatialReference = new ESRI.ArcGIS.Client.Geometry.SpatialReference(wkid)
                });
            }
            points.Add(points[0]);

            System.Collections.ObjectModel.ObservableCollection<ESRI.ArcGIS.Client.Geometry.PointCollection> rings = new System.Collections.ObjectModel.ObservableCollection<ESRI.ArcGIS.Client.Geometry.PointCollection>();
            rings.Add(points);

            ESRI.ArcGIS.Client.Geometry.Polygon polygon = new ESRI.ArcGIS.Client.Geometry.Polygon()
            {
                Rings = rings,
                SpatialReference = new ESRI.ArcGIS.Client.Geometry.SpatialReference(4326)
            };

            return polygon;
        }

        /// <summary>
        /// 获取图形点坐标集合
        /// </summary>
        /// <param name="geometry"></param>
        /// <returns></returns>
        private List<ESRI.ArcGIS.Client.Geometry.MapPoint> GetGeometryPoints(ESRI.ArcGIS.Client.Geometry.Geometry geometry)
        {
            List<ESRI.ArcGIS.Client.Geometry.MapPoint> points = new List<ESRI.ArcGIS.Client.Geometry.MapPoint>();

            switch (geometry.GetType().Name)
            {
                case "Envelope":
                    ESRI.ArcGIS.Client.Geometry.Envelope envelope = geometry as ESRI.ArcGIS.Client.Geometry.Envelope;
                    points.Add(new ESRI.ArcGIS.Client.Geometry.MapPoint()
                    {
                        X = envelope.XMin,
                        Y = envelope.YMax,
                        SpatialReference = geometry.SpatialReference
                    });
                    points.Add(new ESRI.ArcGIS.Client.Geometry.MapPoint()
                    {
                        X = envelope.XMax,
                        Y = envelope.YMax,
                        SpatialReference = geometry.SpatialReference
                    });
                    points.Add(new ESRI.ArcGIS.Client.Geometry.MapPoint()
                    {
                        X = envelope.XMax,
                        Y = envelope.YMin,
                        SpatialReference = geometry.SpatialReference
                    });
                    points.Add(new ESRI.ArcGIS.Client.Geometry.MapPoint()
                    {
                        X = envelope.XMin,
                        Y = envelope.YMin,
                        SpatialReference = geometry.SpatialReference
                    });
                    break;
                case "Polygon":
                    ESRI.ArcGIS.Client.Geometry.Polygon polygon = geometry as ESRI.ArcGIS.Client.Geometry.Polygon;
                    ESRI.ArcGIS.Client.Geometry.PointCollection ring = polygon.Rings[0];
                    ESRI.ArcGIS.Client.Geometry.PointCollection pts = ring as ESRI.ArcGIS.Client.Geometry.PointCollection;
                    for (int i = 0; i < pts.Count; i++)
                    {
                        points.Add(pts[i]);
                    }
                    break;
                default:
                    break;
            }
            points.Add(points[0]);

            return points;
        }

        /// <summary>
        /// 直角坐标转经纬度
        /// </summary>
        /// <param name="x"></param>
        /// <param name="y"></param>
        /// <returns></returns>
        private double[] XYToLonLat(double x, double y)
        {
            var lon = x / 20037508.34 * 180;
            var lat = y / 20037508.34 * 180;
            lat = 180 / Math.PI * (2 * Math.Atan(Math.Exp(lat * Math.PI / 180)) - Math.PI / 2);
            return new double[] { lon, lat };
        }

        /// <summary>
        /// 获取文件扩展名和图标
        /// </summary>
        /// <param name="extension"></param>
        /// <param name="icon"></param>
        /// <param name="gsDataSetType"></param>
        private void GetDownloadFileTypeAndIco(out string extension, out BitmapImage icon, string gsDataSetType)
        {
            icon = new BitmapImage(new Uri(string.Format("{0}Images\\FileIcon\\zip.png", AppDomain.CurrentDomain.BaseDirectory)));
            extension = ".tar.gz";
            return;

            //hdf文件
            if (gsDataSetType.Contains("MOD"))
            {
                icon = new BitmapImage(new Uri(string.Format("{0}Images\\FileIcon\\hdf.png", AppDomain.CurrentDomain.BaseDirectory)));
                extension = ".hdf";
            }
            else if (gsDataSetType.Contains("MYD"))
            {
                icon = new BitmapImage(new Uri(string.Format("{0}Images\\FileIcon\\hdf.png", AppDomain.CurrentDomain.BaseDirectory)));
                extension = ".hdf";
            }
            else if (gsDataSetType == "OLI_TIRS" || gsDataSetType == "L7slc-off" || gsDataSetType == "L7slc-on" || gsDataSetType == "L45TM" || gsDataSetType == "L45MSS" || gsDataSetType == "L123MSS" || gsDataSetType == "L45MSS")
            {
                icon = new BitmapImage(new Uri(string.Format("{0}Images\\FileIcon\\zip.png", AppDomain.CurrentDomain.BaseDirectory)));
                extension = ".tar.gz";
            }
            else if (gsDataSetType == "ali" || gsDataSetType.Contains("hyp"))
            {
                icon = new BitmapImage(new Uri(string.Format("{0}Images\\FileIcon\\tgz.png", AppDomain.CurrentDomain.BaseDirectory)));
                extension = ".tgz";
            }
            else if (gsDataSetType == "co" || gsDataSetType == "no2" || gsDataSetType == "o3" || gsDataSetType == "pm10" || gsDataSetType == "pm25" || gsDataSetType == "so2")
            {
                icon = new BitmapImage(new Uri(string.Format("{0}Images\\FileIcon\\bmp.png", AppDomain.CurrentDomain.BaseDirectory)));
                extension = ".tif";
            }
            else
            {
                icon = new BitmapImage(new Uri(string.Format("{0}Images\\FileIcon\\zip.png", AppDomain.CurrentDomain.BaseDirectory)));
                extension = ".zip";
            }
        }

        #endregion

    }
}
